'use strict';

const Service = require('egg').Service;

const { formatPage } = require('../../utils/index');
// 默认返回的用户基本信息字段
const { USER_DEFAULT_MODEL } = require('../../utils/common');

class UserService extends Service {
	/**
	 * 分页查询用户数据
	 * @returns { Object } { count : 总数目 , rows : [] 查询的数据结果}
	 */
	async list({ currentPage, pageNumber }) {
		currentPage = currentPage || 1;
		pageNumber = pageNumber || 10;
		const { offset, limit } = formatPage(currentPage, pageNumber);
		const queryParams = {
			attributes: USER_DEFAULT_MODEL,
			limit,
			offset
		};
		// 通过 findAndCountAll 返回查询的结果和 所有的结果数
		const result = await this.ctx.model.User.findAndCountAll(queryParams);

		return {
			page: {
				currentPage: currentPage,
				pageNumber: pageNumber,
				offset: offset,
				limit: limit,
				totalNumber: result.count
			},
			list: result.rows
		};
	}

	async info(id) {
		if (!id) return null;
		return await this.ctx.model.User.findOne({
			attributes: USER_DEFAULT_MODEL,
			where: {
				id
			}
		});
	}

	async deleteUserById(id) {
		if (!id) return null;
		return await this.ctx.model.User.destroy({
			where: {
				id
			}
		});
	}

	async updateUserInfoById(params) {
		let id = params.id;
		if (!id) return null;
		return await this.ctx.model.User.update(
			{
				...params
			},
			{
				where: {
					id
				}
			}
		);
	}
}

module.exports = UserService;
